package com.rlz.base.base

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import com.trello.rxlifecycle2.LifecycleTransformer
import com.rlz.base.tools.factory.RepositoryFactory.Companion.createModel
import java.lang.reflect.ParameterizedType

/**
 * Created by RLZ
 * on 2021/10/18
 *
 */
abstract class BaseViewModel<M : BaseModel>(application: Application) :
    AndroidViewModel(application) {

    protected lateinit var mRepository: M

    init {
        createRepository()
    }

    @Suppress("UNCHECKED_CAST")
    private fun createRepository() {
        val type = javaClass.genericSuperclass as ParameterizedType
        val actualTypeArguments = type.actualTypeArguments
        val clazz = actualTypeArguments[0]
        mRepository = createModel(clazz as Class<M>) as M

        if (mRepository !is EmptyModel)
            mRepository.setNetTags(ArrayList())
    }

    fun setObjectLifecycleTransformer(lifecycleTransformer: LifecycleTransformer<Any>) {
        mRepository.setObjectLifecycleTransformer(lifecycleTransformer)
    }
}